using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;

namespace Common.Configuration.Mongo
{
    public class MongoConfig : ConfigurationSection, IMongoConfig
    {
        private const string HostsPropertyName = "Hosts";
        private const string EncodingStringPropertyName = "Encoding";
        private const string LoginPropertyName = "Login";
        private const string PasswordPropertyName = "Password";
        private const string IsReplicaPropertyName = "IsReplica";
        private const string DatabaseNamePropertyName = "DatabaseName";
        private const string DefaultPortPropertyName = "DefaultPort";
        private const string SectionName = "MongoConfig";

        public static MongoConfig Load()
        {
            var cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var section = cfg.GetSection(SectionName);
            return (MongoConfig) section;
        }


        public IList<string> Hosts { get { return HostsCollection.Cast<HostElement>().Select(h=>h.HostName).ToArray(); } }

        public Encoding DbEncoding
        {
            get { return Encoding.GetEncoding(EncodingString); }
            set { EncodingString = value.WebName; }
        }

        [ConfigurationProperty(HostsPropertyName)]
        public HostsCollection HostsCollection
        {
            get { return (HostsCollection) this[HostsPropertyName]; }
            set { this[HostsPropertyName] = value; }
        }

        [ConfigurationProperty(EncodingStringPropertyName)]
        public string EncodingString
        {
            get { return (string)this[EncodingStringPropertyName]; }
            set { this[EncodingStringPropertyName] = value; }
        }

        [ConfigurationProperty(LoginPropertyName)]
        public string Login
        {
            get { return (string)this[LoginPropertyName]; }
            set { this[LoginPropertyName] = value; }
        }

        [ConfigurationProperty(PasswordPropertyName)]
        public string Password
        {
            get { return (string)this[PasswordPropertyName]; }
            set { this[PasswordPropertyName] = value; }
        }

        [ConfigurationProperty(IsReplicaPropertyName)]
        public bool IsReplica
        {
            get { return (bool)this[IsReplicaPropertyName]; }
            set { this[IsReplicaPropertyName] = value; }
        }

        [ConfigurationProperty(DatabaseNamePropertyName)]
        public string DatabaseName
        {
            get { return (string)this[DatabaseNamePropertyName]; }
            set { this[DatabaseNamePropertyName] = value; }
        }

        [ConfigurationProperty(DefaultPortPropertyName)]
        public int DefaultPort
        {
            get { return (int)this[DefaultPortPropertyName]; }
            set { this[DefaultPortPropertyName] = value; }
        }
    }
}